<template>
  <el-upload
    class="avatar-uploader"
    :action="uploadAction"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :headers="headers"
  >
    <img v-if="imgUrl" :src="imgUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import { UserGetterEnum } from '../_/vue/store/user'
export default {
  name: 'XuUpload',
  props: {
    value: String
  },
  watch: {
    value (val) {
      this.imgUrl = val
    },
    imgUrl (val) {
      this.$emit('input', val)
    }
  },
  data () {
    return {
      imgUrl: this.value
    }
  },
  computed: {
    headers () {
      return { Authorization: this.$store.getters[UserGetterEnum.TOKEN] }
    },
    uploadAction () {
      return this.$baseUrl + '/upload'
    }
  },
  methods: {
    beforeAvatarUpload (file) {
      const allowTypes = ['image/png', 'image/jpeg']
      const isJPG = allowTypes.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleAvatarSuccess (res, file) {
      this.imgUrl = res.data.url
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  min-width: 178px;
  height: 178px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.avatar {
  min-width: 178px;
  height: 178px;
  display: inline-block;
}
</style>
